package cn.timelost.elasticsearch.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author JiangYiFan
 * @date 2021/5/4
 */
@Service
public class MovieService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 获取列表
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> searchAll() throws IOException {
        SearchRequest searchRequest = new SearchRequest("movie");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(builder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    /**
     * 通过分类获取列表
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> searchByType(String typeName) throws IOException {
        SearchRequest searchRequest = new SearchRequest("movie");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("type", typeName);
        builder.query(matchQueryBuilder);
        builder.sort(new FieldSortBuilder("score").order(SortOrder.DESC));
        searchRequest.source(builder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    /**
     * 获取分类
     * @return
     * @throws IOException
     */
    public List tagList() throws IOException {
        SearchRequest searchRequest = new SearchRequest("movie");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("group_type").field("type.keyword").size(9);
        sourceBuilder.aggregation(termsAggregationBuilder);
        searchRequest.source(sourceBuilder);

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        List<? extends Terms.Bucket> buckets = ((Terms) aggregations.get("group_type")).getBuckets();
//        System.out.println(JSON.toJSONString(aggregations));
        return buckets;
    }

    /**
     * 分页条件，获取ES中的数据
     * @param searchName 搜索条件
     * @return
     */
    public List<Map<String, Object>> search(String searchName) throws IOException {

        SearchRequest searchRequest = new SearchRequest("movie");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //分页
//        builder.from(pageNo);
//        builder.size(pageSize);

        //精准匹配
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", searchName);
//        builder.query(termQueryBuilder);

        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", searchName);
        builder.query(matchQueryBuilder);

        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //1、要高亮的字段
        highlightBuilder.field("title");
        //关闭多个高亮显示
        highlightBuilder.requireFieldMatch(false);
        //2、高亮字段，前缀
        highlightBuilder.preTags("<span style='color:red'>");
        //3、高亮字段，后缀
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(builder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        System.out.println(JSON.toJSON(response));
        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //原来没有高亮的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title != null) {
                Text[] fragments = title.fragments();
                String newTitle = "";
                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                //将‘高亮字段’替换掉‘原来的内容’即可
                sourceAsMap.put("title", newTitle);
            }
            //上面的if语句内的替换，可以用下面的这一句代替
            //sourceAsMap.put("title", Stream.of(title.fragments()).map(Text::toString).collect(Collectors.joining("")))
            list.add(sourceAsMap);
        }
        return list;
    }
}
